package com.sxfq.loansupermarket.backsystem.modular.remoteSynergy.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.Dept;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.remoteSynergy.entity.SfInfo;
import com.sxfq.loansupermarket.backsystem.modular.remoteSynergy.entity.TongJiInfo;
import com.sxfq.loansupermarket.backsystem.modular.remoteSynergy.entity.*;
import com.sxfq.loansupermarket.backsystem.modular.remoteSynergy.service.ICaseSelectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;


/**
 * @author py
 * @Date
 */
@Controller
@RequestMapping("/caseSelection")
public class CaseSelectionController extends BaseController {
    @Autowired
    ICaseSelectionService service;

    @Autowired
    private SqlMapper sqlMapper;

    private String PREFIX = "/remoteSynergy/";

    /**
     * 跳转到市场预约  未到
     */
    @RequestMapping("")
    public String to_caseSelection(Model model) {
        String tableHead = ShiroKit.getSessionAttr("abbreviation");
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "/case_selection.html";
    }

    /**
     * 跳转到角色分配页面
     */
    @RequestMapping("/getExplanationPage/{label}")
    public String roleAssign(@PathVariable String label, Model model) {
        if (ToolUtil.isEmpty(label)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ShiroKit.getSessionAttr(label+"explanationInfoList") == null) {
            String getListSql = "select id as id, label as label, content as content, num as num from case_selection_explanation_info where label='"+label+"' limit 1;";
            ExplanationInfo explanationInfo = sqlMapper.selectOne(getListSql, ExplanationInfo.class);
            ShiroKit.setSessionAttr(label+"explanationInfoList", explanationInfo);
        }
        model.addAttribute("explanationInfo", ShiroKit.getSessionAttr(label+"explanationInfoList"));
        model.addAttribute("label", label);
        return PREFIX + "explanationPage.html";
    }

    @RequestMapping("/to_goback/{id}")
    public String to_goback(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getSessionAttr("abbreviation");
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("id", id);
        return PREFIX + "/goback.html";
    }

    //查看改动日志
    @RequestMapping("/getIntelligentScoreDetailsList/{id2}")
    @ResponseBody
    public Object getUpdateLogList(@PathVariable String id2, SearchCaseSelectionIntelligentScoreInfo info, HttpServletRequest request) {
        Page<CaseSelectionIntelligentScoreInfo> page = new PageFactory<CaseSelectionIntelligentScoreInfo>().defaultPage();
        try {
            info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
            info.setLimitIndex(page.getSize());
            page.setCurrent(0);
            info.setId2(id2);
            List<CaseSelectionIntelligentScoreInfo> list = service.getIntelligentScoreDetailsList(page, info);
            if (list.size() == 0) {
                info.setStartIndex(0);
                list = service.getIntelligentScoreDetailsList(page, info);
            }
            page.setRecords(list);
            page.setTotal(service.getIntelligentScoreDetailsCount(page, info));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    /**
     * 病例上传管理列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object getInfoList(SearchCaseSelectionInfo info, HttpServletRequest request) {
        Page<CaseSelectionInfo> page = new PageFactory<CaseSelectionInfo>().defaultPage();
        try {
            if (info != null) {
                if (info.getIsSelection() == 2) {
                    info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
                    info.setLimitIndex(page.getSize());
                    page.setCurrent(0);
                    List<CaseSelectionInfo> list = service.selectPageListByQueryGetGoBack(page, info);
                    if (list.size() == 0) {
                        info.setStartIndex(0);
                        list = service.selectPageListByQueryGetGoBack(page, info);
                    }
                    page.setTotal(service.getByQueryGetGoBackPagesCount(page, info));
                    page.setRecords(list);
                } else {
                    info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
                    info.setLimitIndex(page.getSize());
                    page.setCurrent(0);
                    List<CaseSelectionInfo> list = service.selectPageListByQueryGetMap(page, info);
                    if (list.size() == 0) {
                        info.setStartIndex(0);
                        list = service.selectPageListByQueryGetMap(page, info);
                    }
                    page.setTotal(service.getQueryPagesCount(page, info));
                    page.setRecords(list);
                }
            } else {
                info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
                info.setLimitIndex(page.getSize());
                page.setCurrent(0);
                List<CaseSelectionInfo> list = service.selectPageListByQueryGetMap(page, info);
                if (list.size() == 0) {
                    info.setStartIndex(0);
                    list = service.selectPageListByQueryGetMap(page, info);
                }
                page.setTotal(service.getQueryPagesCount(page, info));
                page.setRecords(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    /**
     * 病例评分统计数量
     */
    @RequestMapping("/caseSelectiontotal")
    @ResponseBody
    public List<TongJiInfo> caseSelectiontotal(SearchCaseSelectionInfo searchInfo, HttpServletRequest request) {
        return service.caseSelectiontotal(searchInfo);
    }

    //评分
    @RequestMapping(value = "/addCaseScore", method = RequestMethod.POST)
    @ResponseBody
    public int addCaseScore(String caseScore, String caseComment, String id, Model model) {
        String sql = "update case_selection_information set case_score='" + caseScore + "' ,case_comment='" + caseComment + "'," +
                " selection_status=1,selection_time='" + DateTimeKit.now() + "' " +
                " where id='" + id + "'";
        return sqlMapper.update(sql);
    }

    @RequestMapping(value = "/goback", method = RequestMethod.POST)
    @ResponseBody
    public int goback(String id, String gobackRemarks, Model model) {
        String sql = "update case_selection_information set save_status=0 where id='" + id + "'";
        String sqlin = "INSERT INTO `go_back_case_info` (`back_time`, `back_admin`, `backed_id`,backed_remark) VALUES\n" +
                "('" + DateTimeKit.now() + "', '" + ShiroKit.getUser().getAccount() + "', '" + id + "', '" + gobackRemarks + "');";
        sqlMapper.update(sql);
        return sqlMapper.insert(sqlin);
    }

    //标签
    @RequestMapping(value = "/addMark", method = RequestMethod.POST)
    @ResponseBody
    public int addMark(String mark, String id, Model model) {
        String sql = "update case_selection_information set mark='" + mark + "' where id='" + id + "'";
        return sqlMapper.update(sql);
    }

    @RequestMapping(value = "/to_mark_label")
    public String to_mark_label(Model model) {
        return PREFIX + "add_mark_label.html";
    }

    @RequestMapping(value = "/addCustomMark", method = RequestMethod.POST)
    @ResponseBody
    public int addCustomMark(String customMark, String title, Model model) {
        String sql = "insert into custom_mark_info (custom_mark,user) value ('" + customMark + "','" + ShiroKit.getUser().getAccount() + "')";
        return sqlMapper.insert(sql);
    }

    @RequestMapping(value = "/getMarkList", method = RequestMethod.POST)
    @ResponseBody
    public List<SfInfo> getMarkList() {
        List<SfInfo> list = service.getMarkList();
        return list;
    }

    @RequestMapping(value = "/deleteMarkLabel", method = RequestMethod.POST)
    @ResponseBody
    public int deleteMarkLabel(String mark) {
        String sql = "delete from custom_mark_info where custom_mark='" + mark + "' and user='" + ShiroKit.getUser().getAccount() + "'";
        return sqlMapper.delete(sql);
    }

    /**
     * 创建时暂存病例
     */
    @RequestMapping(value = "/selectionstorage")
    @ResponseBody
    public int selectionstorage(@Valid CaseSelectionUploadInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        return service.insert(info);
    }

    /**
     * 提交修改病例
     */
    @RequestMapping(value = "/selectionsubmitTo")
    @ResponseBody
    public int selectionsubmitTo(@Valid CaseSelectionUploadInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        info.setSelectionTime(DateTimeKit.now());
        return service.update(info);
    }

    @RequestMapping(value = "/getOutpatientSelectionList", method = RequestMethod.POST)
    @ResponseBody
    public List<Dept> getOutpatientSelectionList() {
        List<Dept> list = service.getOutpatientSelectionList();
        return list;
    }

    @RequestMapping(value = "/getCaseOfOutpatientList", method = RequestMethod.POST)
    @ResponseBody
    public List<CaseSelectionUploadInfo> getCaseOfOutpatientList(String applyOutpatient, HttpServletResponse response) {
        List<CaseSelectionUploadInfo> list = service.getCaseOfOutpatientList(applyOutpatient);
        return list;
    }
}